import express from "express";
import React from "react";
import { renderToPipeableStream } from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";
import App from "./src/App";

const app = express();

app.use("/assets", express.static("assets"));
app.use("/dist", express.static("dist"));
app.get("/api/project", (req, res) => {
  res.json([
    {
      id: 1,
      name: "node",
    },
  ]);
});

app.get("/*", (request, response) => {
  const { pipe } = renderToPipeableStream(
    <StaticRouter location={request.url}>
      <App />
    </StaticRouter>,
    {
      bootstrapScripts: ["/dist/client.bundle.js"],
      onShellReady() {
        response.statusCode = 200;
        response.setHeader("content-type", "text/html");
        pipe(response);
      },
      onShellError(error) {
        response.statusCode = 500;
        response.setHeader("content-type", "text/html");
        response.send("<h1>出错了</h1>");
      },
      onError(error) {
        console.error(error);
      },
    }
  );
});

app.listen(8080, () => {
  console.log("ssr初体验：http://127.0.0.1:8080");
});
